package com.atguigu.edu.app.dws;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.bean.UserActRefBean;
import com.atguigu.edu.util.ClickHouseUtil;
import com.atguigu.edu.util.DateFormatUtil;
import com.atguigu.edu.util.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.functions.RichReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import java.time.Duration;

//活跃和回流
public class DwsUserUserActRefWindow {
    public static void main(String[] args) throws Exception {
        //TODO 1 获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //设置并行度
        env.setParallelism(1);

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //TODO 2 设置检查点和状态后端
        /*
        env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
        env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME", "atguigu");
         */

        // TODO 3 读取kafka主题page_log数据
        String topicName = "dwd_traffic_page_log";
        String groupId = "dws_user_user_act_ref_window";
        DataStreamSource<String> streamSource = env.addSource(KafkaUtil.getKafkaConsumer(topicName, groupId));

        // TODO 4 过滤加转换用户登录数据
        SingleOutputStreamOperator<JSONObject> JsonObjStream =
                streamSource.flatMap(new FlatMapFunction<String, JSONObject>() {
                    @Override
                    public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                        JSONObject jsonObject = JSON.parseObject(value);
                        JSONObject common = jsonObject.getJSONObject("common");
                        JSONObject page = jsonObject.getJSONObject("page");
                        // 判断是否为登录用户数据
                        if (common.getString("uid") != null && page.getString("last_page_id") == null) {
                            out.collect(jsonObject);
                        }
                    }
                });

        JsonObjStream.print("json>>>");


        // TODO 5 设置水位线
        SingleOutputStreamOperator<JSONObject> beanWithWatermarkStream = JsonObjStream.assignTimestampsAndWatermarks(WatermarkStrategy
                .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        return element.getLong("ts");
                    }
                }));

        // TODO 6 根据uid聚合，以及登录时间的状态去重
        SingleOutputStreamOperator<UserActRefBean> beanStream =
                beanWithWatermarkStream.keyBy(s -> s.getJSONObject("common").getString("uid"))
                        .flatMap(new RichFlatMapFunction<JSONObject, UserActRefBean>() {
                            ValueState<String> lastLoginDtState = null;

                            @Override
                            public void open(Configuration parameters) throws Exception {
                                lastLoginDtState =
                                        getRuntimeContext().getState(new ValueStateDescriptor<String>(
                                                "last_login_dt", String.class));
                            }

                            @Override
                            public void flatMap(JSONObject value, Collector<UserActRefBean> out) throws Exception {
                                String lastLoginDt = lastLoginDtState.value();
                                Long ts = value.getLong("ts");
                                String loginDt = DateFormatUtil.toYmdHms(ts);
                                if (lastLoginDt == null || !lastLoginDt.equals(loginDt)) {
                                    if (lastLoginDt != null && (ts - DateFormatUtil.toTs(lastLoginDt,true)) > 24 * 60 * 60 * 1000L * 7) {
                                        out.collect(new UserActRefBean("", "", 1L, 1L, ts));
                                        lastLoginDtState.update(loginDt);
                                    }
                                    out.collect(new UserActRefBean("", "", 0L, 1L, ts));
                                    lastLoginDtState.update(loginDt);

                                }
                            }
                        });

        beanStream.print("bean>>>");

        SingleOutputStreamOperator<UserActRefBean> resultStream =
                beanStream.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                        .reduce(new ReduceFunction<UserActRefBean>() {
                            @Override
                            public UserActRefBean reduce(UserActRefBean value1, UserActRefBean value2) throws Exception {
                                value1.setActiveCt(value1.getActiveCt() + value2.getActiveCt());
                                value1.setReflowCt(value1.getReflowCt() + value2.getReflowCt());
                                return value1;

                            }
                        }, new AllWindowFunction<UserActRefBean, UserActRefBean, TimeWindow>() {
                            @Override
                            public void apply(TimeWindow window, Iterable<UserActRefBean> values,
                                              Collector<UserActRefBean> out) throws Exception {
                                UserActRefBean userActRefBean = values.iterator().next();
                                userActRefBean.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                                userActRefBean.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                                userActRefBean.setTs(System.currentTimeMillis());
                                out.collect(userActRefBean);
                            }
                        });

        resultStream.print("result>>>");
        resultStream.addSink(ClickHouseUtil.getClickHouseSinkFunc("insert into dws_user_user_act_ref_window values (?,?,?,?,?)"));


        // TODO  执行任务
        env.execute();
    }
}
